import DCYX_STUDY_API from '@/api/dcyx/study.api'
import DCYX_PROGRAM_API, {
  type ProgramItem,
  type UpdateUserCurrentProgramPayload,
  CurrentProgram,
} from '@/api/dcyx/program.api'
import { store } from '@/store'
import DCYX_UNITS_API, { UnitCountWordItem } from '@/api/dcyx/units.api'
import { useDcyxUnitStoreHook } from './dcyx_unit.store'

export const useDcyxProgramStore = defineStore('dcyx_program', () => {
  const currentProgram = ref<CurrentProgram>({} as CurrentProgram)

  const inited = ref(false)
  const currentUnitCountWord = ref<UnitCountWordItem>({} as UnitCountWordItem)

  const programList = ref<ProgramItem[]>([])
  const currentProgramId = ref<number>(0)
  const currentSeriesId = ref<number>(0)

  // const currentProgramId = computed(() => dcyxUnitStore.currentUnit?.programId)
  // const currentSeriesId = computed(() => dcyxUnitStore.currentUnit?.seriesId)

  function setCurrentProgramId(programId: number) {
    currentProgramId.value = programId
  }
  function setCurrentSeriesId(seriesId: number) {
    currentSeriesId.value = seriesId
  }

  /**
   * 获取系列下的学习项目
   * @param {number} seriesId 系列ID
   * @returns {ProgramItem[]} 学习项目列表
   */
  function getProgramBySeriesId(seriesId: number) {
    return new Promise<ProgramItem[]>((resolve, reject) => {
      DCYX_PROGRAM_API.getProgramBySeriesId({
        pageNum: 1,
        pageSize: 50,
        seriesId,
      })
        .then((res: any) => {
          programList.value = res.list
          resolve(res.list)
        })
        .catch((error: any) => {
          programList.value = []
          reject(error)
        })
        .finally(() => {})
    })
  }

  /**
   * 获取单元单词数量
   * @param {string} seriesId 系列ID
   * @param {string} programId 学习项目ID
   * @param {string} unitName 单元名称
   * @returns {UnitCountWordItem} 单元单词数量
   */
  // function countWordsByUnit(
  //   seriesId: string,
  //   programId: string,
  //   unitName: string,
  // ) {
  //   return new Promise<UnitCountWordItem>((resolve, reject) => {
  //     DCYX_PROGRAM_API.countWordsByUnit(seriesId, programId, unitName)
  //       .then((res: UnitCountWordItem) => {
  //         resolve(res)
  //       })
  //       .catch((error: any) => {
  //         reject(error)
  //       })
  //       .finally(() => {})
  //   })
  // }

  /**
   * [post] 更新用户选中当前教材项的接口
   * @param {UpdateUserCurrentProgramPayload} data
   */
  function updateUserCurrentProgram(data: UpdateUserCurrentProgramPayload) {
    return new Promise((resolve, reject) => {
      DCYX_PROGRAM_API.updateCurrentUserProgram(data)
        .then((res) => {
          resolve(res)
        })
        .catch((error) => {
          reject(error)
        })
        .finally(() => {})
    })
  }

  /**
   * [get] 获取当前学习项目详情-包含信息更多
   * @returns {CurrentProgram}
   */
  function fetchCurrentProgram() {
    return new Promise<CurrentProgram>((resolve, reject) => {
      DCYX_PROGRAM_API.getCurrentProgramDetail()
        .then((res) => {
          console.log('fetchCurrentProgram res', res)
          currentProgram.value = res
          resolve(res)
        })
        .catch((error) => {
          currentProgram.value = {} as CurrentProgram
          reject(error)
        })
        .finally(() => {})
    })
  }

  /**
   * 初始化 program store function
   * 1. 判断 unit STORE 模块是否初始化完毕
   *  1.如果完毕，继续执行；如果没有完毕，则调用 unit store 的初始化；
   * 2. 判断 currentProgramId 是否存在
   *  1.如果存在，则调用 fetchCurrentProgram 获取当前学习项目详情；并且调用 getProgramBySeriesId 获取系列下的学习项目；
   *  2.如果不存在，打印错误；
   */
  async function initProgramStore() {
    console.log('initProgramStore start')
    if (inited.value) return
    // console.log('currentProgramId', currentProgramId.value)
    // if (currentProgramId.value) {
    // currentProgram.value =
    await fetchCurrentProgram()

    if (useDcyxUnitStoreHook().inited) {
      console.log('useDcyxUnitStoreHook().inited')
      // programList.value =
      await getProgramBySeriesId(currentSeriesId.value)
      inited.value = true
      console.log('currentProgramId', currentProgramId.value)
      console.log('currentSeriesId', currentSeriesId.value)
    } else {
      console.error(
        'useDcyxUnitStoreHook().inited false currentSeriesId 不存在',
      )
    }
    // } else {
    // console.error('currentProgramId 不存在')
    // }
  }

  /**
   * 清空 program store
   */
  function resetProgramStore() {
    currentProgram.value = {} as CurrentProgram
    programList.value = []
    inited.value = false
    // 其他需要清空的状态可在此添加
  }

  return {
    currentProgram,
    currentUnitCountWord,
    currentProgramId,
    currentSeriesId,
    programList,
    // loading,
    inited,
    // getCurrentProgram,
    getProgramBySeriesId,
    // countWordsByUnit,
    updateUserCurrentProgram,
    fetchCurrentProgram,
    initProgramStore,
    resetProgramStore,
    setCurrentProgramId,
    setCurrentSeriesId,
  }
})

export function useDcyxProgramStoreHook() {
  return useDcyxProgramStore(store)
}
